//
//  CWTabBarController.swift
//  weibo
//
//  Created by 陈伟 on 15/10/14.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit

class CWTabBarController: UITabBarController {
    
    //MARK:点击撰写微博按钮  大加号
    @objc private func clickAddBtn() {
        //判断是否登录状态
        var vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogin{
            vc = ComposeViewController()
        }else{
            vc = VisitorTableViewController()
        }
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    //MARK:加载视图
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadChildController()
    
        setupComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    
    //懒加载撰写按钮
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
    
}

extension CWTabBarController{
    
    private func setupComposedButton() {
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2*w, 0)
        composedButton.addTarget(self, action: "clickAddBtn", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    private func editViewCancall() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private func loadChildController(){
        
//        tabBar.tintColor = UIColor.orangeColor()
        
        let homeVC = HomeTableViewController()
        addChildViewController(homeVC, title: "主页", imageName: "tabbar_home")
        
        let messageVC = MessageTableViewController()
        addChildViewController(messageVC, title: "消息", imageName: "tabbar_message_center")
//
        addChildViewController(UIViewController())
        
        let discoverVC = DiscoverTableViewController()
        addChildViewController(discoverVC, title: "发现", imageName: "tabbar_discover")
        
        let profileVC = ProfileTableViewController()
        addChildViewController(profileVC, title: "我", imageName: "tabbar_profile")
        
    }
    
    private func addChildViewController(viewController: UIViewController, title: String, imageName: String) {
        
        let nav = UINavigationController(rootViewController: viewController)
        
        nav.tabBarItem.image = UIImage(named: imageName)
        
        viewController.title = title
        addChildViewController(nav)
        
    }

}